//
//  SegmenViewController.m
//  EasyToo
//
//  Created by Jr Lan on 13-8-24.
//
//

#import "SegmenViewController.h"
#import "DeviceUtil.h"

#import "TimeView.h"
#import "PriceView.h"
#import "PassengerViewController.h"

@interface SegmenViewController ()

@end

@implementation SegmenViewController
{
    UISegmentedControl *_segment;
    
    TimeView *_timeView;
    PriceView *_priceView;
    
    BOOL _IsTime;
    
    NSMutableArray *_airArray;
}

@synthesize startCity;
@synthesize arriveCity;
@synthesize startDate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    _airArray = [[NSMutableArray alloc]init];
    
    //等待网络 
    NetworkAlertView *networking = [NetworkAlertView shareView];
    [networking showNetView];
    
    //网络请求
    AirplaneManager *plainmanager = [AirplaneManager shareManager];
    plainmanager.delegate = self;
    [plainmanager searchAirTicket:self.startCityCode
                           toCity:self.arriveCityCode
                          flyTime:self.startDate];
    
    
    //初始化视图
    [self init_view];
}

- (void)dealloc
{
    [_segment release];
    [_timeView release];
    [_priceView release];
    [_airArray release];
    
    _segment = nil;
    _timeView = nil;
    _priceView = nil;
    _airArray = nil;
    
    [super dealloc];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



//初始化视图
- (void)init_view
{
    [self.navigationItem setTitle:@"机票"];
    
    [self initPriceView];
//    [self addPriceView];
//    
//    [self initTimeView];
//    [self initPriceView];
//    
//    [self initSegmentCtrl];
//    
//    [self addTimeView];
//    
//    //下拉刷新的控件添加在tableView上    
//    refreshView = [[EGORefreshTableFooterView alloc]  initWithFrame:CGRectZero];
//    refreshView.delegate = self;
//    [self.view addSubview:refreshView];
//    reloading = NO;
//    
//    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
//
//    [self reloadData];
}

////初始化SegmentCtrl
//- (void)initSegmentCtrl
//{
//    _segment = [[UISegmentedControl alloc] initWithFrame:CGRectMake(0, 0, [DeviceUtil getScreenWidth], 30)];
//    
//    [_segment setSegmentedControlStyle:UISegmentedControlStyleBar];
//    [_segment setBackgroundColor:[UIColor lightGrayColor]];
//    [_segment insertSegmentWithTitle:@"按时间排序" atIndex:0 animated:NO];
//    [_segment insertSegmentWithTitle:@"按价格排序" atIndex:1 animated:NO];
//    
//    [_segment addTarget:self action:@selector(onTabSelected:) forControlEvents:UIControlEventValueChanged];
//    
//    [self.view addSubview:_segment];
//}
//
//-(void)onTabSelected:(id)sender
//{
//    UISegmentedControl *control = (UISegmentedControl *)sender;
//    
//    switch (control.selectedSegmentIndex) {
//        case 0:
//            [self addTimeView];
//            [self removePriceView];
//            break;
//        case 1:
//            [self removeTimeView];
//            [self addPriceView];
//            break;
//        default:
//            break;
//    }
//    
//}
//
//
////按时间排序
//- (void)initTimeView
//{
//    _timeView = [[TimeView alloc] initWithFrame:CGRectMake(0, 30, [DeviceUtil getScreenWidth], 420 - 30)];
//    _timeView.startCity = self.startCity;
//    _timeView.arriveCity = self.arriveCity;
//    _timeView.startDate = self.startDate;
//    _timeView.delegate = self;
//}
//- (void)addTimeView
//{
//    if (_timeView)
//    {
//        _IsTime = YES;
//        [self.view addSubview:_timeView];
//    }
//}
//- (void)removeTimeView
//{
//    if (_timeView)
//    {
//        [_timeView removeFromSuperview];
//    }
//}

//按价格排序
- (void)initPriceView
{
    _priceView = [[PriceView alloc] initWithFrame:CGRectMake(0, 0, [DeviceUtil getScreenWidth], [DeviceUtil getScreenHeight] - ADD_ADJUST_IOS7STATUES_HIGHT)];
}
- (void)addPriceView
{
    if (_priceView)
    {
        _IsTime = NO;
        _priceView.startCity = self.startCity;
        _priceView.arriveCity = self.arriveCity;
        _priceView.startDate = self.startDate;
        _priceView.airArray = _airArray;
        _priceView.delegate = self;
        [self.view addSubview:_priceView];
    }
}
- (void)removePriceView
{
    if (_priceView)
    {
        [_priceView removeFromSuperview];
    }
}



//请求数据
-(void)reloadData
{
    reloading = YES;
    //新建一个线程来加载数据
    [NSThread detachNewThreadSelector:@selector(requestData) toTarget:self withObject:nil];
}

-(void)requestData
{
    //加载新数据
    if (_IsTime == YES) {
        [_timeView getNewData];
    } else {
        [_priceView getNewData];
    }
    
    //sleep(1);
    //在主线程中刷新UI
    [self performSelectorOnMainThread:@selector(reloadUI) withObject:nil waitUntilDone:NO];
}


-(void)reloadUI
{
	reloading = NO;
    
    //停止下拉的动作,恢复表格的便宜
	[refreshView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
    //更新界面
    if (_IsTime == YES) {
        [_timeView.tableview reloadData];
    } else {
        [_priceView.tableview reloadData];
    } 
    [self setRefreshViewFrame];
}

-(void)setRefreshViewFrame
{
    //如果contentsize的高度比表的高度小，那么就需要把刷新视图放在表的bounds的下面
    int height = MAX(self.tableView.bounds.size.height, self.tableView.contentSize.height);
    refreshView.frame =CGRectMake(0.0f, height, self.view.frame.size.width, self.tableView.bounds.size.height);
}

#pragma mark - EGORefreshTableFooterDelegate
//出发下拉刷新动作，开始拉取数据
- (void)egoRefreshTableFooterDidTriggerRefresh:(EGORefreshTableFooterView*)view
{
    [self reloadData];
}

//返回当前刷新状态：是否在刷新
- (BOOL)egoRefreshTableFooterDataSourceIsLoading:(EGORefreshTableFooterView*)view
{
    return reloading;
}

//返回刷新时间
-(NSDate *)egoRefreshTableFooterDataSourceLastUpdated:(EGORefreshTableFooterView *)view
{
    return [NSDate date];
}

#pragma mark - UIScrollView

//此代理在scrollview滚动时就会调用
//在下拉一段距离到提示松开和松开后提示都应该有变化，变化可以在这里实现
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [refreshView egoRefreshScrollViewDidScroll:scrollView];
}

//松开后判断表格是否在刷新，若在刷新则表格位置偏移，且状态说明文字变化为loading...
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [refreshView egoRefreshScrollViewDidEndDragging:scrollView];
}

#pragma mark timeviewdelegate

- (void)onClickTableItem:(OrderAirInfo*)orderInfo;
{
    PassengerViewController *passViewController = [[PassengerViewController alloc]init];
    passViewController.orderInfo = orderInfo;
    passViewController.startCity = self.startCity;
    passViewController.arriveCity = self.arriveCity;
    passViewController.startDate = self.startDate;
    passViewController.userArray = [[[NSMutableArray alloc] init] autorelease];
    [self.navigationController pushViewController:passViewController animated:YES];
    [passViewController release];
}

//查询机票
- (void)qryPlainInfo:(BOOL)isSuccess
             AirInfo:(AirPlaceInfo*)airInfo
{
    //取消等待
    NetworkAlertView *networking = [NetworkAlertView shareView];
    [networking delView];
    
    if ([airInfo.airList count] == 0) {
        UIAlertView* baseAlert = [[[UIAlertView alloc] initWithTitle:@"该航班这个时间段未有开通" message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil] autorelease];
        [baseAlert show];
    }
    
    for (int i = 0; i < [airInfo.airList count]; i++) {
        AirInfo *tempAirInfo = [airInfo.airList objectAtIndex:i];

        for (int j = 0; j < [tempAirInfo.classArray count]; j++) {
            ClassInfo *classInfo = [tempAirInfo.classArray objectAtIndex:j];
            
            OrderAirInfo *orderInfo = [[OrderAirInfo alloc] init];
            orderInfo.fltno = tempAirInfo.fltno;
            orderInfo.sc = tempAirInfo.sc;
            orderInfo.scAirdrome = tempAirInfo.scAirdrome;
            orderInfo.ec = tempAirInfo.ec;
            orderInfo.ecAirdrome = tempAirInfo.ecAirdrome;
            orderInfo.deptime = tempAirInfo.deptime;
            orderInfo.arrtime = tempAirInfo.arrtime;
            orderInfo.planesty = tempAirInfo.planesty;
            orderInfo.stopnum = tempAirInfo.stopnum;
            orderInfo.etkt = tempAirInfo.etkt;
            orderInfo.meal = tempAirInfo.meal;
            
            orderInfo.classname = classInfo.classname;
            orderInfo.num = classInfo.num;
            orderInfo.saleprice = classInfo.saleprice;
            orderInfo.classcode = classInfo.classcode;
            orderInfo.buildfee = classInfo.buildfee;
            orderInfo.fuelfee = classInfo.fuelfee;
            orderInfo.isApply = classInfo.isApply;
            orderInfo.tgqInfo = classInfo.tgqInfo;
            orderInfo.aheadDays = classInfo.aheadDays;
            
            [_airArray addObject:orderInfo];
        }
    }

    //初始化视图
    [self addPriceView];
}

@end


